// 生成数独谜题的工具函数
export const generateSudokuPuzzle = (size = 6, difficulty = 20) => {
  const grid = Array(size).fill().map(() => Array(size).fill(0));
  const nums = Array.from({length: size}, (_, i) => i + 1);

  // 获取方块大小
  const getBoxSize = (size) => {
    if (size === 9) return { rows: 3, cols: 3 };
    if (size === 6) return { rows: 2, cols: 3 };
    if (size === 4) return { rows: 2, cols: 2 };
    throw new Error('不支持的数独大小');
  };

  const boxSize = getBoxSize(size);

  // 检查数字是否有效
  const isValid = (row, col, num) => {
    // 检查行
    for (let x = 0; x < size; x++) {
      if (grid[row][x] === num) return false;
    }
    // 检查列
    for (let x = 0; x < size; x++) {
      if (grid[x][col] === num) return false;
    }
    // 检查方块
    const boxRow = Math.floor(row / boxSize.rows) * boxSize.rows;
    const boxCol = Math.floor(col / boxSize.cols) * boxSize.cols;
    for (let i = 0; i < boxSize.rows; i++) {
      for (let j = 0; j < boxSize.cols; j++) {
        if (grid[boxRow + i][boxCol + j] === num) return false;
      }
    }
    return true;
  };

  // 打乱数组
  const shuffle = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  };

  // 解决数独
  const solve = (row = 0, col = 0) => {
    if (col === size) {
      row++;
      col = 0;
    }
    if (row === size) return true;

    if (grid[row][col] !== 0) return solve(row, col + 1);

    const shuffledNums = shuffle([...nums]);
    for (const num of shuffledNums) {
      if (isValid(row, col, num)) {
        grid[row][col] = num;
        if (solve(row, col + 1)) return true;
        grid[row][col] = 0;
      }
    }
    return false;
  };

  // 生成完整的数独解决方案
  solve();

  // 移除一些数字来创建谜题
  let removed = 0;
  while (removed < difficulty) {
    const row = Math.floor(Math.random() * size);
    const col = Math.floor(Math.random() * size);
    if (grid[row][col] !== 0) {
      grid[row][col] = 0;
      removed++;
    }
  }

  return grid;
}; 